<?php
/**
 * NfxRegionAgent.php
 *
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2015-2025 山西牛酷信息科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.niushop.com.cn
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : niuteam
 * @date : 2015.1.17
 * @version : v1.0.0.0
 */

namespace addons\Nsfx\data\service;

use addons\Nsfx\data\model\NfxPromoterRegionAgentApplyModel;
use addons\Nsfx\data\model\NfxPromoterGoodsModel;
use addons\Nsfx\data\model\NfxPromoterGoodsCouponReleaseModel;
use addons\Nsfx\data\model\NfxPromoterModel;
use data\model\NsGoodsCategoryModel;
use addons\Nsfx\data\model\NfxShareGoodsModel;

use data\service\BaseService;
use data\service\Config;
use data\service\Member\MemberCoupon;

use think\Log;

/**
 * 分销商品
 */
class NfxGoods extends BaseService
{
    private $promoter_level = [
        [
            'level' => 'middle',
            'level_name' => '中级红旗手',
        ],
        [
            'level' => 'high',
            'level_name' => '高级红旗手',
        ],
        [
            'level' => 'supper',
            'level_name' => '特级红旗手',
        ],
    ];
    /**
     * 获取区域代理分类
     */
    public function getRegionAgentCategory($uid)
    {
        $category_ids = $this->getRegionAgentCategoryIds($uid);
        //查询分类
        $category_model = new NsGoodsCategoryModel();
        $category_list = $category_model->getQuery(['category_id' => ['in', $category_ids]], 'category_id, category_name, category_pic', 'sort asc');
        return $category_list;
    }

    /**
     * 查询分类ids
     * @param $uid
     * @return string
     */
    private function getRegionAgentCategoryIds($uid)
    {
        //获取所有已通过的申请
        $apply_model = new NfxPromoterRegionAgentApplyModel();
        $apply_list = $apply_model->getQuery(['uid' => $uid, 'audit_status' => 'confirm_pass'], 'category_ids', 'apply_id asc');

        //获取申请过的分类ids
        $category_ids_arr = [];
        foreach($apply_list as $key=>$val){
            $category_ids_arr[] = $val['category_ids'];
        }
        $category_ids = join(',', $category_ids_arr);
        return $category_ids;
    }

    /**
     * 获取区域代理分类下的商品
     */
    public function getRegionAgentCategoryGoods($params, $page_index = 1, $page_size = 0)
    {
        $uid = $params['uid'];
        $category_id = $params['category_id'];
        $goods_id = isset($params['goods_id'])? $params['goods_id'] : 0;
		
		//获取推广员id
		$promoter_model = new NfxPromoterModel();
		$promoter_info = $promoter_model->getInfo(['uid' => $uid], 'promoter_id');
		$promoter_id = $promoter_info['promoter_id'];

        $promoter_goods_model = new NfxPromoterGoodsModel();
        $alias = 'pg';
        $join = [
            ['ns_goods g', 'pg.goods_id = g.goods_id', 'left'],
            ['ns_goods_category gc', 'gc.category_id = g.category_id'],
        ];
        $order = 'pg.id asc';
        $field_arr = [
            "pg.goods_id, count(*) as middle_num",
            "g.goods_name",
            "gc.category_name"
        ];
        $field = join(',', $field_arr);
        $group = 'g.goods_id';

        //查询条件
        $condition = [
            'pg.confirm_status' => 1,
            'pg.parent_promoter' => $promoter_id,
            'g.category_id' => ['in', $this->getRegionAgentCategoryIds($uid)]
        ];
        if($category_id != 0) $condition['g.category_id'] = $category_id;
        if($goods_id != 0) $condition['g.goods_id'] = $goods_id;//查询某一个具体的产品

        $order = trim($order);
        $count = $promoter_goods_model
            ->alias($alias)
            ->join($join)
            ->where($condition)
            ->group($group)
            ->count();
        if ($page_size == 0) {
            $list = $promoter_goods_model
                ->field($field)
                ->alias($alias)
                ->join($join)
                ->where($condition)
                ->order($order)
                ->group($group)
                ->select();
            $page_count = 1;
        } else {
            $start_row = $page_size * ($page_index - 1);
            $list = $promoter_goods_model
                ->field($field)
                ->alias($alias)
                ->join($join)
                ->where($condition)
                ->order($order)
                ->limit($start_row . "," . $page_size)
                ->group($group)
                ->select();
            if ($count % $page_size == 0) {
                $page_count = $count / $page_size;
            } else {
                $page_count = (int) ($count / $page_size) + 1;
            }
        }

        //统计中级红旗手的总数
        $total_middle_num = $promoter_goods_model
            ->alias($alias)
            ->join($join)
            ->where($condition)
            ->count();

        return array(
            'data' => $list,
            'total_count' => $count,
            'page_count' => $page_count,
            'total_middle_num' => $total_middle_num,
        );
    }

    /**
     * 获取推广商品 用于我的成就
     */
    public function getPromoterGoods($params, $page_index = 1, $page_size = 0)
    {
        $uid = $params['uid'];
        $level = $params['level'];
        $category_id = $params['category_id'];

        $promoter_goods_model = new NfxPromoterGoodsModel();
        $alias = 'pg';
        $join = [
            ['ns_goods g', 'pg.goods_id = g.goods_id', 'left'],
            ['sys_album_picture p', 'g.picture = p.pic_id', 'left'],
        ];
        $order = 'pg.id asc';
        $field_arr = [
            "pg.goods_id, pg.level, pg.middle_num",
            "g.goods_name",
            "p.pic_cover_big, p.pic_cover_mid, p.pic_cover_small"
        ];
        $field = join(',', $field_arr);

        //查询条件
        $condition = [
            'pg.confirm_status' => 1,
            'pg.uid' => $uid,
        ];
        if($level != '') $condition['pg.level'] = $level;
        if($category_id != 0) $condition['g.category_id'] = $category_id;

        $list = $promoter_goods_model->pageQuery($page_index, $page_size, $condition, $order, $field, $alias, $join);

        foreach($list['data'] as $key=>$val){
            $list['data'][$key]['level_name'] = $this->getPromoterLevelName($val['level']);
            $level_data = $this->getPromoterLevelData($val['level'], $val['middle_num']);
            $list['data'][$key]['total_num'] = $level_data['total_num'];
            $list['data'][$key]['percent'] = $level_data['percent'];
        }

        return $list;
    }

    /**
     * 获取推广商品下级推广员 用于产品下红旗手列表
     */
    public function getPromoterGoodsLowerPromoter($params, $page_index = 1, $page_size = 0)
    {
        $uid = $params['uid'];
        $goods_id = $params['goods_id'];

        //获取推广员id
        $promoter_model = new NfxPromoterModel();
        $promoter_info = $promoter_model->getInfo(['uid' => $uid], 'promoter_id');
        $promoter_id = $promoter_info['promoter_id'];

        $promoter_goods_model = new NfxPromoterGoodsModel();
        $alias = 'pg';
        $join = [
            ['sys_user u', 'pg.uid = u.uid', 'left'],
        ];
        $condition = [
            'pg.confirm_status' => 1,
            'pg.parent_promoter' => $promoter_id,
            'pg.goods_id' => $goods_id,
        ];
        $order = 'pg.id asc';
        $field_arr = [
            "pg.level, pg.middle_num",
            "u.user_name, u.nick_name, u.user_headimg, u.reg_time",
        ];
        $field = join(',', $field_arr);
        $list = $promoter_goods_model->pageQuery($page_index, $page_size, $condition, $order, $field, $alias, $join);

        $config_service = new Config();
        $right_set = $config_service->getRightConfig();
        foreach($list['data'] as $key=>$val){
            $list['data'][$key]['level_name'] = $this->getPromoterLevelName($val['level']);
            $list['data'][$key]['promoter_icon'] = $right_set['value']['promoter_icon'];
        }
        return $list;
    }

    /**
     * 获取推广员等级 用于红旗手等级筛选
     */
    public function getPromoterLevel()
    {
        return $this->promoter_level;
    }

    /**
     * 获取推广员等级 用于红旗手等级筛选
     */
    public function getPromoterLevelName($level)
    {
        $promoter_level = $this->promoter_level;
        $level_name = '';
        foreach($promoter_level as $key=>$val){
            if($val['level'] == $level){
                $level_name = $val['level_name'];
                break;
            }
        }
        return $level_name;
    }

    /**
     * 处理红旗手等级数据
     */
    public function getPromoterLevelData($level, $middle_num)
    {
        static $reward_set = null;
        if(!$reward_set){
            $config_service = new Config();
            $reward_set = $config_service->getRewardConfig();
        }
        $res = [];
        switch($level){
            case 'middle':
                $res['total_num'] = $reward_set['value']['high_condition_num'];
                break;
            case 'high':
            case 'supper':
                $res['total_num'] = $reward_set['value']['supper_condition_num'];
                break;
        }
        $res['percent'] = floor($middle_num / $res['total_num'] * 100);
        if($res['percent'] > 100) $res['percent'] = 100;
        return $res;
    }

    /**
     * 获取推广商品分类 用于品类筛选
     */
    public function getPromoterGoodsCategory($uid)
    {
        $promoter_goods_model = new NfxPromoterGoodsModel();
        $list = $promoter_goods_model
            ->alias('pg')
            ->join([
                ['ns_goods g', 'g.goods_id = pg.goods_id'],
            ])
            ->field('*')
            ->where(['pg.uid' => $uid, 'pg.confirm_status' => 1])
            ->group('g.category_id')
            ->select();
        $category_id_arr = [];
        foreach($list as $key=>$val){
            $category_id_arr[] = $val['category_id'];
        }
        $category_ids = join(',', $category_id_arr);

        //查询分类
        $category_model = new NsGoodsCategoryModel();
        $category_list = $category_model->getQuery(['pid' => 0, 'is_visible' => 1, 'category_id' => ['in', $category_ids]], 'category_id, category_name, category_pic', 'sort asc');
        return $category_list;
    }

    /**
     * 获取推广商品数据
     */
    public function getPromoterGoodsInfo($condition, $field = '*')
    {
        $promoter_goods_model = new NfxPromoterGoodsModel();
        $promoter_goods_info = $promoter_goods_model->getInfo($condition, $field);
        return $promoter_goods_info;
    }

    /*********************************** 优惠券相关 **********************************/

    /**
     * 添加优惠券发放记录
     * $type 是现在发还是下次发
     * 思路：
     * 1、查找配置，
     * 2、确定发放时间，
     * 3、添加记录，
     * 4、等待发放
     */
    public function addCouponReleaseRecord($pg_id, $type = 'next')
    {
        //查看配置
        $config_service = new Config();
        $reward_set = $config_service->getRewardConfig();
        $coupon_time_set = $reward_set['value']['coupon_time_set'];

        //判断剩余时间是否足够
        $promoter_goods_model = new NfxPromoterGoodsModel();
        $promoter_goods_info = $promoter_goods_model->getInfo(['id' => $pg_id]);
        $remain_free_time = $promoter_goods_info['remain_free_time'];
        if($remain_free_time < $coupon_time_set) return 1;

        //是否现在发放
        if($type == 'now'){
            $time = time() + 60;
        }else{
            $time = time() + $coupon_time_set * 3600 * 24 * 30;
        }

        //添加记录
        $coupon_release_model = new NfxPromoterGoodsCouponReleaseModel();
        $data = [
            'pg_id' => $pg_id,
            'time' => $time
        ];
        $res = $coupon_release_model->save($data);
        return $res;
    }

    /**
     * 发放优惠券
     * 思路：
     * 1、查找配置，
     * 2、确定发放数量，
     * 3、发放，
     * 4、修改状态，
     * 5、再添加优惠券发放记录
     */
    public function releaseCoupon()
    {
        $member_coupon = new MemberCoupon();
        $promoter_goods_model = new NfxPromoterGoodsModel();

        //查看配置
        $config_service = new Config();
        $reward_set = $config_service->getRewardConfig();
        $coupon_num_set = $reward_set['value']['coupon_num_set'];
        $coupon_time_set = $reward_set['value']['coupon_time_set'];

        //查询可以发放的优惠券
        $day_start = strtotime(date('Y-m-d'));
        $day_end = $day_start + 3600 * 24;
        $coupon_release_model = new NfxPromoterGoodsCouponReleaseModel();
        $release_list = $coupon_release_model->getQuery([
            'time' => [
                ['egt', $day_start],
                ['elt', $day_end]
            ],
            'status' => 0,
        ]);

        //循环发放
        $promoter_goods_model->startTrans();
        try{
            foreach($release_list as $key=>$val){
                $promoter_goods_info = $promoter_goods_model->getInfo(['id' => $val['pg_id']]);
                //发放优惠券
                $member_coupon->releaseFreeCoupon($promoter_goods_info['goods_id'], $promoter_goods_info['uid'], $coupon_num_set, $coupon_time_set);
                //修改状态
                $coupon_release_model->save(['num' => $coupon_num_set, 'status' => 1], ['id' => $val['id']]);
                $promoter_goods_model->where(['id' => $val['pg_id']])->setDec('remain_free_time', $coupon_num_set);
                //再添加优惠券发放记录
                $this->addCouponReleaseRecord($val['pg_id']);
            }
            $promoter_goods_model->commit();
            return 1;
        }catch(\Exception $e){
            $promoter_goods_model->rollback();
            Log::write('发放优惠券报错---' . $e->getMessage());
            return $e->getMessage();
        }
    }

    /**
     * 推广商品确认
     */
    public function confirmPromoterGoods()
    {
        $nfx_user = new NfxUser();
        Log::write('进入推广商品确认');
        //确认检测时间
        if(false == $nfx_user->confirmTimeCheck()) return 1;

        //奖励设置
        $config_service = new Config();
        $reward_set = $config_service->getRewardConfig();

        //查询时间条件和数量限制
        $confirm_time_condition = $nfx_user->getConfirmTimeCondition();
        $confirm_num_limit = $nfx_user->getConfirmLimit();

        //查询所有要操作的记录
        $promoter_goods_model = new NfxPromoterGoodsModel();
        $promoter_goods_list = $promoter_goods_model
            ->field('*')
            ->where(['confirm_status' => 0, 'create_time' => ['elt', $confirm_time_condition]])
            ->limit($confirm_num_limit)
            ->order('create_time asc')
            ->select();
        Log::write('进入推广商品列表---');
        Log::write($promoter_goods_list);

        $promoter_model = new NfxPromoterModel();
        $promoter_goods_model->startTrans();
        try{
            foreach($promoter_goods_list as $key=>$val)
            {
                //修改状态为已确认
                $promoter_goods_model->update(['confirm_status' => 1], ['id' => $val['id']]);

                //更新推广员已购买商品种类数
                $promoter_model->where(['promoter_id' => $val['promoter_id']])->setInc('goods_num');

                //判断是否需要更新父级的相关数据 如果没有父级则不继续
                if($val['parent_promoter'] == 0) continue;

                //更新父级相对于该产品的红旗手等级和所拥有下级的中级红旗手数量
                $parent_promoter_goods_info = $promoter_goods_model->getInfo(['promoter_id' => $val['parent_promoter'], 'goods_id' => $val['goods_id'], 'confirm_status' => 1]);
                if(empty($parent_promoter_goods_info)) continue;

                $parent_level = $parent_promoter_goods_info['level'];
                $middle_num = $parent_promoter_goods_info['middle_num'] + 1;

                //获取奖励规则配置
                $high_condition_num = $reward_set['value']['high_condition_num'];
                $supper_condition_num = $reward_set['value']['supper_condition_num'];

                //默认更新所拥有中级红旗手数量
                $parent_promoter_goods_data = [
                    'middle_num' => $middle_num,
                ];

                //判断是否升为高级
                if($parent_level == 'middle' && $middle_num >= $high_condition_num){
                    $parent_promoter_goods_data['level'] = 'high';
                    $parent_promoter_goods_data['remain_free_time'] = $parent_promoter_goods_info['remain_free_time'] + $reward_set['value']['high_free_coupon_time'] * 12;
                    $parent_promoter_goods_data['total_free_time'] = $parent_promoter_goods_info['total_free_time'] + $reward_set['value']['high_free_coupon_time'] * 12;
                }

                //判断是否升为特级
                if($parent_level == 'high' && $middle_num >= $supper_condition_num){
                    $parent_promoter_goods_data['level'] = 'supper';
                    $parent_promoter_goods_data['remain_free_time'] = $parent_promoter_goods_info['remain_free_time'] + $reward_set['value']['supper_free_coupon_time'] * 12;
                    $parent_promoter_goods_data['total_free_time'] = $parent_promoter_goods_info['total_free_time'] + $reward_set['value']['supper_free_coupon_time'] * 12;
                }
                $promoter_goods_model->update($parent_promoter_goods_data, [
                    'promoter_id' => $val['parent_promoter'],
                    'goods_id' => $val['goods_id'],
                ]);

                //添加发放记录
                if($parent_promoter_goods_data['level'] == 'high'){
                    $this->addCouponReleaseRecord($parent_promoter_goods_info['id'], 'now');
                }
            }
            $promoter_goods_model->commit();
            return 1;
        }catch(\Exception $e){
            $promoter_goods_model->rollback();
            Log::write('推广商品列表报错---' . $e->getMessage());
            return $e->getMessage();
        }
    }

    /*********************************** 商品分享 ***********************************/

    /**
     * 检测商品分享
     * 思路:分享表只记录分享，别的逻辑一概不涉及，只起记录和查询作用
     * @param $share_uid 分享人
     * @param $buyer_uid 购买人
     * @param $goods_id 商品
     */
    public function dealWithGoodsShare($share_uid, $buyer_uid, $goods_id)
    {
        if(empty($share_uid) || empty($buyer_uid) || empty($goods_id) || $share_uid === $buyer_uid){
            return -1;
        }

        $share_goods_model = new NfxShareGoodsModel();
        $share_goods_info = $share_goods_model->getInfo(['buyer_uid' => $buyer_uid, 'goods_id' => $goods_id]);

        if(empty($share_goods_info)){
            $data = [
                'share_uid' => $share_uid,
                'buyer_uid' => $buyer_uid,
                'goods_id' => $goods_id,
            ];
            $res = $share_goods_model->save($data);
        }else{
            $data = [
                'share_uid' => $share_uid,
            ];
            $where = [
                'buyer_uid' => $buyer_uid,
                'goods_id' => $goods_id,
            ];
            $res = $share_goods_model->save($data, $where);
        }
        return $res;
    }

    /**
     * 获取商品分享信息
     * @param $buyer_uid
     * @param $goods_id
     */
    public function getGoodsShare($buyer_uid, $goods_id)
    {
        $share_goods_model = new NfxShareGoodsModel();
        $share_goods_info = $share_goods_model->getInfo(['buyer_uid' => $buyer_uid, 'goods_id' => $goods_id]);
        return $share_goods_info;
    }
}